package com.abso.mp3tunes.locker.ui.actions;

import java.util.Arrays;
import java.util.List;

import com.abso.mp3tunes.locker.ui.LockerImages;
import com.abso.mp3tunes.locker.ui.LockerPlugin;
import com.abso.mp3tunes.locker.ui.viewers.LockerViewer;
import com.abso.mp3tunes.locker.ui.views.MusicPlayerView;

/**
 * Action able to enque a set of tracks into the music player.
 */
public class PlayAction extends AbstractLockerViewerAction {

	/** The selected elements. */
	private List elements;

	/**
	 * Constructs a new action.
	 * 
	 * @param lockerViewer
	 *            the Locker tree viewer.
	 */
	public PlayAction(LockerViewer lockerViewer) {
		super("Play", LockerImages.getDescriptor(LockerImages.PLAY),
				lockerViewer);
	}

	/**
	 * Sets the current selection.
	 * 
	 * @param elements
	 *            the selected elements.
	 */
	public void setSelectedElements(List elements) {
		this.elements = elements;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.eclipse.jface.action.Action#run()
	 */
	public void run() {
		final MusicPlayerView musicPlayer = LockerPlugin.getDefault()
				.showMusicPlayer();
		if (musicPlayer != null) {

			/*
			 * to avoid blocking the UI thread waiting for the jobs to complete
			 * (see Job.join) we span a new thread
			 */
			new Thread() {
				public void run() {
					musicPlayer
							.setTracks(Arrays.asList(unwrapTracks(elements)));

					/*
					 * here we need to return to the UI thread to update the
					 * player
					 */
					runUIAsync(new Runnable() {
						public void run() {
							musicPlayer.stop();
							musicPlayer.play();
						}
					});
				}
			}.start();
		}
	}

}
